//
//  TaskDetailViewController.swift
//  ToDoList
//
//  Created by Qingke on 16/4/13.
//  Copyright © 2016年 Qingke. All rights reserved.
//

import UIKit

protocol TaskDetailDelegate: class {
    func addTaskViewController(controller: TaskDetailViewController,task: Task)
    func editTaskViewController(controller: TaskDetailViewController,task: Task)

}


class TaskDetailViewController: UITableViewController ,UITextFieldDelegate{
    
    @IBOutlet weak var textFiled: UITextField!
    @IBOutlet weak var savaButton: UIBarButtonItem!
    
    weak var taskDetaildelegate: TaskDetailDelegate?
    var taskToEdit:Task?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        savaButton.enabled = false
        if let taskToEdit = taskToEdit {
            self.textFiled.text = taskToEdit.name
            self.navigationItem.title = "编辑任务"
        }
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(true)
        textFiled.becomeFirstResponder()
    }
    
    @IBAction func savaButton(sender: AnyObject) {
        
        if let taskToEdit = taskToEdit {
            taskToEdit.name = textFiled.text!
            taskDetaildelegate!.editTaskViewController(self, task: taskToEdit)
//            print(taskToEdit)
            
        } else {
            if let checkListVC = taskDetaildelegate {
                let task = Task()
                task.name = textFiled.text!
                checkListVC.addTaskViewController(self, task: task)
            }
            
        }
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    @IBAction func cancelButton(sender: UIBarButtonItem) {
        dismissViewControllerAnimated(true, completion: nil)
    }
  
    override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
        return nil
    }
    
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        let oldtext:NSString = textFiled.text!
        let newText:NSString = oldtext.stringByReplacingCharactersInRange(range, withString: string)
        
        if newText.length > 0 {
            savaButton.enabled = true
        } else {
            savaButton.enabled = false
        }
        
        
        return true
    }

}
